// qpidserver.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"


#include <qpid/messaging/Address.h>
#include <qpid/messaging/Connection.h>
#include <qpid/messaging/Message.h>
#include <qpid/messaging/Receiver.h>
#include <qpid/messaging/Sender.h>
#include <qpid/messaging/Session.h>

#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <sstream>
#include <iostream>
#include <unordered_map>
using namespace qpid::messaging;

using std::stringstream;
using std::string;

int main(int argc, char** argv) {
	const char* url = "amqp:tcp:127.0.0.1:5672";
	std::string connectionOptions = "";

	Connection connection;
	try {
		connection = Connection(url);
		connection.open();
		Session session = connection.createSession();
		Receiver receiver = session.createReceiver("amq.topic");
		Message message;

		std::unordered_map < std::string, Sender> senderMap;
		while (receiver.fetch(message)) {
			std::cout << message.getContentBytes() << std::endl;
			message.setContentBytes("echo:" + message.getContentBytes());
			Address rspAddress = message.getReplyTo();
			const auto& sender = senderMap.find(rspAddress.str());
			if (sender == senderMap.end()) {
				senderMap[rspAddress.str()] = session.createSender(rspAddress);;
				senderMap[rspAddress.str()].send(message);
			} else {
				sender->second.send(message);
			}
			
			session.acknowledge();
		}

		receiver.close();
		session.close();
		connection.close();
	}
	catch (const std::exception& error) {
		std::cout << "Error: " << error.what() << std::endl;
		connection.close();
	}
	system("pause");
	return 1;
}